package db;

import java.util.List;

import javax.jdo.PersistenceManager;


import utils.SysInutils;

public class DBUtils {

	static {
		PersistenceFactory.get().getPersistenceManager();
	}

	public static String genPassHash(String password) {
		return SysInutils.getHashMD5(password);
	}

	public static DBUser getUser(String key) {
		for (DBUser user : getAllUsers()) {
			if (user.getName().equals(key)) {
				return user;
			}
		}
		return null;
	}

	public static List<DBUser> getAllUsers() {
		PersistenceManager pm = PersistenceFactory.get().getPersistenceManager();
		String query = "select from " + DBUser.class.getName();
		return (List<DBUser>) pm.newQuery(query).execute();
	}

	public static void createUser(String name, String pass, String pis, boolean isAdm) {
		DBUser dbUser = new DBUser(name, genPassHash(pass), pis, isAdm);
		PersistenceManager pm = PersistenceFactory.get().getPersistenceManager();
		try {
			pm.makePersistent(dbUser);
		} finally {
			pm.close();
		}
	}

}
